<template>
  <a-modal :title="title" :width="800" v-model:visible="visible" @ok="onSubmit">
    <a-form ref="formRef" :model="form" :rules="rules" :label-col="{ span: 7 }">
      <a-row>
        <a-col v-for="(i, idx) in appform" :key="idx + 'b'" :span="16">
          <a-form-item v-if="i.show" :label="i.label" :name="i.name">
            <a-input v-if="i.type === 'input' && i.name !== 'secret'" v-model:value="i.value" @change="valueChange" />
            <a-radio-group v-if="i.type === 'radio'" v-model:value="i.value" button-style="solid">
              <a-radio-button v-for="(e, num) in i.options" :value="e.value">{{ e.label }}</a-radio-button>
            </a-radio-group>
            <a-select
              v-if="i.type === 'select'"
              v-model:value="i.value"
              :mode="i.mode || ''"
              @change="i.change($event, i.name)"
              :options="i.options"
            ></a-select>
            <a-textarea v-if="i.type === 'textarea'" v-model:value="i.value" :auto-size="{ minRows: 2, maxRows: 5 }" />
            <a-switch v-if="i.type === 'switch'" v-model:checked="i.value" :checkedValue="1" :unCheckedValue="0">
              <template #checkedChildren><check-outlined /></template>
              <template #unCheckedChildren><close-outlined /></template>
            </a-switch>
            <UploadImg v-if="i.type === 'img'" v-model:value="i.value"></UploadImg>
            <UploadFile v-if="i.type === 'upFile'" v-model:value="i.value" />
            <a-radio-group v-model:value="i.value" v-if="i.type === 'radiobutton'" @change="selectChange(i)">
              <a-radio-button value="static">静态</a-radio-button>
              <a-radio-button value="dynamic">动态</a-radio-button>
              <a-radio-button value="app" disabled>应用</a-radio-button>
            </a-radio-group>
            <a-time-picker v-if="i.type === 'timepicker'" v-model:value="i.value" format="HH:mm" valueFormat="HH:mm" />
            <a-tree-select
              v-if="i.type === 'treeSelects'"
              v-model:value="i.value"
              style="width: 100%"
              :tree-data="treeData"
              :dropdown-style="{ maxHeight: '600px', overflow: 'auto' }"
              tree-checkable
              allow-clear
              tree-default-expand-all
              :show-checked-strategy="SHOW_PARENT"
              tree-node-filter-prop="title"
              :fieldNames="{ title: 'title', key: 'key', value: 'key' }"
              @change="valueChange"
            />
          </a-form-item>
        </a-col>
      </a-row>
    </a-form>
  </a-modal>
</template>
<script setup>
import { ref, nextTick, reactive, toRaw, onMounted } from 'vue';
import { message, TreeSelect } from 'ant-design-vue';
import _ from 'lodash';
import UploadImg from '/@/components/file/img.vue';
import UploadFile from '/@/components/file/uploadFile.vue';
import { smartSentry } from '/@/lib/smart-sentry';
import { applicationManagementApi } from '/@/api/system/applicationManagement-api';
import { configureApi } from '../../../../api/system/configure-api.js';
import { permissionsApi } from '/@/api/access/permissions';
import dayjs from 'dayjs';

// 基本信息form
const appform = ref([
  { label: '编码', name: 'roleCode', value: '', type: 'input', options: [], disabled: false, show: true },
  { label: '角色名称', name: 'roleName', value: '', type: 'input', options: [], disabled: false, show: true },
  { label: '类型', name: 'category', value: 'static', type: 'radiobutton', options: [], disabled: false, show: true },
  { label: '加入时间', name: 'resumeTime', value: '', type: 'timepicker', options: [], disabled: false, show: false },
  { label: '挂起时间', name: 'suspendTime', value: '', type: 'timepicker', options: [], disabled: false, show: false },
  { label: ' 部门列表', name: 'orgIdsList', value: '', type: 'treeSelects', options: [], disabled: false, show: false },
  // { label: ' 属性过滤器', name: 'filters', value: '', type: 'textarea', options: [], disabled: false, show: false },
  { label: ' 描述', name: 'description', value: '', type: 'textarea', options: [], disabled: false, show: true },
]);

const activeKey = ref(0);
// emit
const emit = defineEmits(['reload']);

// 组件ref
const formRef = ref();

const formDefault = {
  id: undefined,
};
let form = reactive({ ...formDefault });
const rules = {
  name: [{ required: true, message: '请输入应用名称', trigger: 'blur' }],
};
// 是否展示抽屉
const visible = ref(false);
const formType = ref(null);
const title = ref('');

function showDrawer(rowData, index, type) {
  title.value = type;
  formType.value = index;

  if (index) {
    //添加
    onClose();
    appform.value.forEach((i) => {
      form[i.name] = i.value;
      if (i.type == 'timepicker') {
        i.value = '00:00';
      }
      if (i.name == 'category') {
        i.value = 'static';
        selectChange(i);
      }
    });
  } else {
    //编辑
    appform.value.forEach((i) => {
      i.value = rowData[i.name] || '';
      form[i.name] = i.value;
      if (i.name == 'category') {
        selectChange(i);
      }
      if (i.name == 'orgIdsList') {
        if (i.value) {
          i.value = i.value
            .split(',')
            .map((item) => item.trim())
            .filter((item) => item !== '');
          console.log(i.value);
        }
      }
    });
    Object.assign(paramObj, rowData);
  }

  Object.assign(form, formDefault);
  visible.value = true;
}

//添加之前清空
function onClose() {
  Object.assign(form, formDefault);
  appform.value.forEach((i) => {
    i.value = i.defaultValue || '';
    if (i.name == 'orgIdsList') {
      if (i.value) {
        i.value = i.value
          .split(',')
          .map((item) => item.trim())
          .filter((item) => item !== '');
      }
    }
  });
  visible.value = false;
}

const paramObj = {};

function valueChange() {
  Object.assign(paramObj);

  paramObj['switch_status'] = true;

  appform.value.forEach((i) => {
    if (i.name === 'select_authorizedGrantTypes' && i.value && i.value.length) {
      paramObj['authorizedGrantTypes'] = i.value.join(',');
    } else if (i.name === 'select_scope' && i.value && i.value.length) {
      paramObj['scope'] = i.value.join(',');
    } else if (i.name == 'orgIdsList') {
      paramObj[i.name] =
        Object.values(i.value)
          .map(Number) // 将每个值转换为数字
          .join(', ') + ',';
    } else {
      paramObj[i.name] = i.value;
    }
  });
  Object.assign(form, paramObj);
}

const treeData = ref([]);
// 获取树形数据
function getTree() {
  configureApi.getOrgsTree().then((res) => {
    if (res.data.nodes.length) {
      treeData.value = buildTree(res.data.nodes);
    }
  });
}
const SHOW_PARENT = TreeSelect.SHOW_PARENT;
function buildTree(data) {
  const tree = [];
  const map = {};
  // 先把所有节点放入一个映射表
  data.forEach((item) => {
    map[item.key] = { title: item.title, key: item.key, parentKey: item.parentKey, children: [] };
  });

  // 构建树
  data.forEach((item) => {
    const { parentKey } = item;
    if (parentKey === '0') {
      // 如果是根节点
      tree.push(map[item.key]);
    } else {
      // 如果有父节点，则将当前节点添加到父节点的 children 中
      if (map[parentKey]) {
        map[parentKey].children.push(map[item.key]);
      }
    }
  });
  return tree;
}

let list = [];
function selectChange(obj) {
  appform.value.forEach((i) => {
    if (i.name == 'orgIdsList') {
      i.value = [];
    }
  });

  if (obj.name == 'category') {
    if (list.length) {
      list.forEach((i) => {
        appform.value[i].show = false;
      });
    }
    if (obj.value == 'static') {
      list = [];
    } else if (obj.value == 'dynamic') {
      list = [3, 4, 5];
    }
    list.forEach((i) => {
      appform.value[i].show = true;
    });
  }
  valueChange();
}

async function onSubmit() {
  valueChange();

  formRef.value
    .validate()
    .then(async () => {
      // SmartLoading.show();
      try {
        let res;
        //1 新增  0编辑
        if (formType.value == 1) {
          res = await permissionsApi.addRoles(paramObj);
        } else {
          if (paramObj.filters) {
            delete paramObj.filters;
          }
          res = await permissionsApi.updateRoles(paramObj);
        }

        message.success(`${form.id ? '修改' : '添加'}成功`);
        onClose();
        emit('reload');
      } catch (error) {
        smartSentry.captureError(error);
      } finally {
        // SmartLoading.hide();
      }
    })
    .catch((error) => {
      console.log('error', error);
      message.error('参数验证错误，请仔细填写表单数据!');
    });
}
onMounted(() => {
  getTree();
});
defineExpose({
  showDrawer,
});
</script>
